package com.itany.controller;

import com.alibaba.fastjson.JSON;
import com.itany.entity.User;
import com.itany.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Author：汤小洋
 * Date：2023-01-31 13:49
 * Description：<描述>
 */
@RestController
public class RedisController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("/test1")
    public String test1(){
        // System.out.println(redisTemplate.getConnectionFactory().getConnection());

        /**
         * 操作String
         */
        // redisTemplate.opsForValue().set("name","alice");
        // redisTemplate.opsForValue().set("age","20",10, TimeUnit.SECONDS);
        // redisTemplate.opsForValue().setIfAbsent("address","上海",5,TimeUnit.MINUTES); // 当key不存在时才设置
        // System.out.println(redisTemplate.opsForValue().get("address"));

        /**
         * 操作List
         */
        // redisTemplate.opsForList().leftPush("names","aaa");
        // redisTemplate.opsForList().leftPush("names","bbb");
        // redisTemplate.opsForList().leftPush("names","ccc");
        // redisTemplate.opsForList().leftPushAll("names","aaa","bbb","ccc");
        // System.out.println(redisTemplate.opsForList().range("names",0,1));

        /**
         * 操作Set、ZSet、Hash
         */
        // redisTemplate.opsForSet()
        // redisTemplate.opsForZSet()
        // redisTemplate.opsForHash().put("user","name","tom");
        // redisTemplate.opsForHash().put("user","age","20");
        // redisTemplate.opsForHash().put("user","sex","male");
        // System.out.println(redisTemplate.opsForHash().get("user","sex"));

        /**
         * 存储对象数据
         */
        // User user = new User(1001, "zhangsan", "123");
        // redisTemplate.opsForValue().set("user", JSON.toJSONString(user));
        //
        // String str = redisTemplate.opsForValue().get("user");
        // User u = JSON.parseObject(str, User.class);
        // System.out.println(u);


        /**
         * Key操作
         */
        redisTemplate.delete("user");


        return "";
    }


    @RequestMapping("/test2")
    public String test2(){
        redisUtil.set("name","tom");
        System.out.println(redisUtil.get("name"));
        return "";
    }
}
